//
//  TDBindingCardTableViewController.m
//  TFB
//
//  Created by yull on 15/8/15.
//  Copyright (c) 2015年 TD. All rights reserved.
//

#import "TDBindingCardTableViewController.h"
#import "TDBindingCardPicView.h"
#import "TDProvince.h"
#import "TDSelectLocationTableViewController.h"
#import "TDCommonData.h"
#import "TDSelectBankNameTableViewController.h"

#define HANDHELD 202
#define FRONT    201

@interface TDBindingCardTableViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate>

@property (nonatomic, assign) NSInteger takeImgTag;
@property (nonatomic, strong) TDBindingCardPicView *headerView;

@property (nonatomic, strong) NSArray *leftArray;
@property (nonatomic, strong) NSArray *placeholderArray;

@property (nonatomic, strong) NSString *sendHandheldImage;
@property (nonatomic, strong) NSString *sendFrontImage;
@property (nonatomic, strong) NSString *cardNo;
@property (nonatomic, strong) NSString *cardName;
@property (nonatomic, strong) TDProvince *province;
@property (nonatomic, strong) TDCity *city;
@property (nonatomic, strong) TDArea *area;

@end

@implementation TDBindingCardTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.navigationItem.title = @"绑定银行卡";
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.leftArray = @[@"银行卡号", @"银行名称", @"开户城市"];
    self.placeholderArray = @[@"请输入储蓄卡号", @"请点击选择银行名称", @"请点击选择（省 市/区）"];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, CGRectGetWidth(self.tableView.frame), 80)];
    footerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    UIButton *commitB = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    commitB.frame = CGRectMake(10, 16, CGRectGetWidth(self.tableView.frame) - 20, 44);
    commitB.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    commitB.backgroundColor = MainColor;
    [commitB setTitle:@"下一步" forState:0];
    [commitB setTitleColor:[UIColor whiteColor] forState:0];
    commitB.layer.cornerRadius = 5;
    commitB.layer.masksToBounds = YES;
    [commitB addTarget:self action:@selector(onClickNextBtn:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:commitB];
    
    self.tableView.tableFooterView = footerView;
    
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    [self initData];
}

- (void)initData
{
    self.cardNo = [TDCommonData defaultInstance].bcCardNo;
    self.cardName = [TDCommonData defaultInstance].bcCardName;
    self.province = [TDCommonData defaultInstance].bcProvince;
    self.city = [TDCommonData defaultInstance].bcCity;
    self.area = [TDCommonData defaultInstance].bcArea;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)onClickNextBtn:(id)sender
{
    if (!self.sendHandheldImage.length) {
        [self.navigationController.view makeToast:@"请拍摄手持身份证正面照" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.sendFrontImage.length) {
        [self.navigationController.view makeToast:@"请拍摄身份证正面照" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.province || !self.city || !self.area) {
        [self.navigationController.view makeToast:@"请选择开户城市" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.cardNo.length) {
        [self.navigationController.view makeToast:@"请输入储蓄卡号" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.cardName.length) {
        [self.navigationController.view makeToast:@"请选择银行名称" duration:2.0f position:@"center"];
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [TDHttpEngine requestForUpBankCardWithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID]
                                      custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE]
                                        OperType:@"1"
                                       oldCardNo:nil
                                          cardNo:self.cardNo
                                        cardName:self.cardName
                                       cardFront:self.sendFrontImage
                                        cardBack:self.sendHandheldImage
                                      provinceId:self.province.provId
                                          cityId:self.city.cityId
                                          areaId:self.area.areaId
                                        bankcode:self.area.bankcode
                                       cnapsCode:nil
                                        complete:^(BOOL succeed, NSString *msg, NSString *cod) {
                                            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                            if (succeed) {
                                                
                                                [TDUser defaultUser].cardBundingStatus = @"1";
                                                [self.navigationController.view makeToast:msg duration:2.0f position:@"center"];
                                                [self performSelector:@selector(popToRoot) withObject:self afterDelay:2.0f];
                                            } else {
                                                [self.navigationController.view makeToast:msg duration:2.0f position:@"center"];
                                            }
                                        }];
}

- (void)popToRoot
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)getPhoto:(UIButton *)sender
{
    _takeImgTag = sender.tag;
    
#if !SIMULATOR
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType =UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
    else{
        [self.view makeToast:@"该设备没有摄像头" duration:2.0f position:@"center"];
    }
#else
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePicker animated:YES completion:nil];
#endif
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"照片信息--%@", info);
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    while (imageData.length > 200*1024) {
        image = [self scaleImage:image toScale:0.5];
        imageData = UIImageJPEGRepresentation(image, 0.5);
    }
    
    switch (_takeImgTag) {
        case HANDHELD:{
//            [self.headerView.handHoldBtn setImage:nil forState:0];
            [self.headerView.handHoldBtn setBackgroundImage:image forState:0];
            _sendHandheldImage = [imageData base64EncodedString];
            [TDCommonData defaultInstance].bcHandHoldImage = image;
        }
            break;
        case FRONT:{
//            [self.headerView.frontBtn setImage:nil forState:0];
            [self.headerView.frontBtn setBackgroundImage:image forState:0];
            _sendFrontImage = [imageData base64EncodedString];
            [TDCommonData defaultInstance].bcFrontImage = image;
        }
            break;
            
        default:
            break;
    }
}

//重新绘制图片的尺寸
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return scaledImage;
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (section == 0) {
        return 1;
    }
    
    return self.leftArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 116;
    }
    
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identifier = @"picIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        
        if (nil == cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            TDBindingCardPicView *view = [TDBindingCardPicView instanceView];
            view.frame = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
            [view.handHoldBtn addTarget:self action:@selector(getPhoto:) forControlEvents:UIControlEventTouchUpInside];
            [view.frontBtn addTarget:self action:@selector(getPhoto:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:view];
            self.headerView = view;
        }
        
        if ([TDCommonData defaultInstance].bcHandHoldImage) {
            [self.headerView.handHoldBtn setImage:nil forState:0];
            [self.headerView.handHoldBtn setBackgroundImage:[TDCommonData defaultInstance].bcHandHoldImage forState:0];
            NSData *imageData = UIImageJPEGRepresentation([TDCommonData defaultInstance].bcHandHoldImage, 0.5);
            _sendHandheldImage = [imageData base64EncodedString];
        }
        
        if ([TDCommonData defaultInstance].bcFrontImage) {
            [self.headerView.frontBtn setImage:nil forState:0];
            [self.headerView.frontBtn setBackgroundImage:[TDCommonData defaultInstance].bcFrontImage forState:0];
            NSData *imageData = UIImageJPEGRepresentation([TDCommonData defaultInstance].bcFrontImage, 0.5);
            _sendFrontImage = [imageData base64EncodedString];
        }
        
        return cell;
    }
    
    static NSString *identifier = @"realnameIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UILabel *leftL = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, 80, 40)];
        leftL.font = [UIFont systemFontOfSize:14];
        leftL.textColor = [UIColor grayColor];
        leftL.tag = 1001;
        [cell.contentView addSubview:leftL];
        
        UITextField *rightTF = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftL.frame), 2, self.view.frame.size.width - 10 - CGRectGetMaxX(leftL.frame), 40)];
        rightTF.font = [UIFont systemFontOfSize:17];
        rightTF.delegate = self;
        rightTF.tag = 1002;
        [cell.contentView addSubview:rightTF];
    }
    
    UILabel *leftL = (UILabel *)[cell.contentView viewWithTag:1001];
    leftL.text = self.leftArray[indexPath.row];
    
    UITextField *rightTF = (UITextField *)[cell.contentView viewWithTag:1002];
    rightTF.placeholder = self.placeholderArray[indexPath.row];
    
    if (indexPath.row == 4) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    if (indexPath.row == 0) {
        rightTF.text = self.cardNo;
    } else if (indexPath.row == 1) {
        rightTF.text = self.cardName;
    } else {
        if (self.province && self.city && self.area) {
            rightTF.text = [NSString stringWithFormat:@"%@ %@ %@", self.province.provName, self.city.cityName, self.area.areaName];
        } else {
            rightTF.text = @"";
        }
    }
    
    return cell;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField.placeholder isEqualToString:self.placeholderArray.firstObject]) {
        return YES;
    }
    
    [self.view endEditing:YES];
    
    if ([textField.placeholder isEqualToString:self.placeholderArray.lastObject]) {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [TDHttpEngine requestForGetProvinceWithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID] custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE] complete:^(BOOL succeed, NSString *msg, NSString *cod, NSArray *array) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            if (succeed) {
                TDSelectLocationTableViewController *controller = [[TDSelectLocationTableViewController alloc] initWithStyle:UITableViewStylePlain];
                controller.locations = array;
                controller.complete = ^(TDProvince *province, TDCity *city, TDArea *area) {
                    self.province = province;
                    self.city = city;
                    self.area = area;
                    
                    [TDCommonData defaultInstance].bcProvince = province;
                    [TDCommonData defaultInstance].bcCity = city;
                    [TDCommonData defaultInstance].bcArea = area;
                    
                    [self.tableView reloadData];
                };
                
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
                nav.navigationBar.barTintColor = NavigatorBackgroundColor;
                nav.navigationBar.tintColor = [UIColor whiteColor];
                nav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
                [self presentViewController:nav animated:YES completion:nil];
            } else {
                [self.view makeToast:msg duration:2.0f position:@"center"];
            }
        }];
    } else {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [TDHttpEngine requestFor_GETBANKNAME_WithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID] custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE] complete:^(BOOL succeed, NSString *msg, id reqBody) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            if (succeed) {
                NSArray *bankList = [reqBody objectForKey:@"dictList"];
                
                TDSelectBankNameTableViewController *controller = [[TDSelectBankNameTableViewController alloc] initWithStyle:UITableViewStylePlain];
                controller.bankNameArray = bankList;
                controller.complete = ^(NSDictionary *bankInfo) {
                    
                    self.cardName = [bankInfo objectForKey:@"dictName"];
                    [TDCommonData defaultInstance].bcCardName = self.cardName;
                    
                    [self.tableView reloadData];
                };
                
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
                nav.navigationBar.barTintColor = NavigatorBackgroundColor;
                nav.navigationBar.tintColor = [UIColor whiteColor];
                nav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
                [self presentViewController:nav animated:YES completion:nil];
            } else {
                [self.view makeToast:msg duration:2.0f position:@"center"];
            }
        }];
    }
    
    return NO;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *content = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    self.cardNo = content;
    [TDCommonData defaultInstance].bcCardNo = content;
    
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    self.cardNo = textField.text;
    [TDCommonData defaultInstance].bcCardNo = textField.text;
    
    return YES;
}

@end
